package cash_access;

import java.io.IOException;
import java.net.UnknownHostException;

import mware_lib.communication.ObjectStream;
import mware_lib.communication.Server;
import mware_lib.messages.ReqAccMsg;
import mware_lib.messages.ShutdownMsg;

public class AccountSkeleton implements Runnable{
	private volatile boolean running;
    private Thread thread;
    
    private Server server;
    private Account account;
    
    public AccountSkeleton(int accountPort, Account account) throws IOException{
        this.running = true;
        this.thread = new Thread(this);
        this.server = new Server(accountPort);
        this.account = account;
    }

    @Override
    public void run() {
        try {
            while(this.running){
                this.server.accept();
                ObjectStream os = this.server.getObjectStream();
                try {
                    Object rcvdObj = os.receive();
                    if(rcvdObj instanceof ShutdownMsg){
                        this.stop();
                    } else if(rcvdObj instanceof ReqAccMsg){
                        doReq((ReqAccMsg)rcvdObj, os);
                    } else {
                        System.out.println((rcvdObj.getClass().toString()));	
                    }
                } catch (ClassNotFoundException e) {
                    os.send(new ClassNotFoundException(e.getMessage()));
                }
            }
        } catch (UnknownHostException e) { e.printStackTrace();
        } catch (IOException e) { e.printStackTrace();
        }
    }
    
    public void stop(){
        this.running = false;
    }
    
    public void start(){
        this.thread.start();
    }
    
    
    private void doReq(ReqAccMsg msg, ObjectStream os){
        AccountWorker worker = new AccountWorker(this.account, msg, os);
        worker.start();
    }
    
}
